package com.rizhov.iterators;

import com.rizhov.graph.Graph;
import com.rizhov.graph.GraphEdge;
import com.rizhov.gui.MainWindow;

public class IncomingEdgeIterator implements GraphIterator {

    private Graph graph = Graph.getInstance();
    private int currentInEdge = -1;
    private boolean isGoneOut = false;

    @Override
    public void next() {
	MainWindow.iteratorStartIndex = -1;
	MainWindow.iteratorEndIndex = -1;
	while (currentInEdge < graph.getVertexCount()) {
	    currentInEdge++;
	    if (graph.isEdgeExist(currentInEdge, MainWindow.selectedVertexIndex)) {
		MainWindow.iteratorStartIndex = currentInEdge;
		MainWindow.iteratorEndIndex = MainWindow.selectedVertexIndex;
		isGoneOut = false;
		return;
	    }
	}
	isGoneOut = true;
    }

    @Override
    public void setToBegin() {
	MainWindow.iteratorStartIndex = -1;
	MainWindow.iteratorEndIndex = -1;
	currentInEdge = -1;
	while (currentInEdge < graph.getVertexCount()) {
	    currentInEdge++;
	    if (graph.isEdgeExist(currentInEdge, MainWindow.selectedVertexIndex)) {
		MainWindow.iteratorStartIndex = currentInEdge;
		MainWindow.iteratorEndIndex = MainWindow.selectedVertexIndex;
		isGoneOut = false;
		return;
	    }
	}
	isGoneOut = true;
    }

    @Override
    public void setToEnd() {
	MainWindow.iteratorStartIndex = -1;
	MainWindow.iteratorEndIndex = -1;
	currentInEdge = graph.getVertexCount();
	while (currentInEdge >= 0) {
	    currentInEdge--;
	    if (graph.isEdgeExist(currentInEdge, MainWindow.selectedVertexIndex)) {
		MainWindow.iteratorStartIndex = currentInEdge;
		MainWindow.iteratorEndIndex = MainWindow.selectedVertexIndex;
		isGoneOut = false;
		return;
	    }
	}
	isGoneOut = true;
    }

    @Override
    public void setData(Object newData) {
	String[] strArr = (String[]) newData;
	if (graph.isEdgeExist(currentInEdge, MainWindow.selectedVertexIndex)) {
	    graph.setEdgeWeight(currentInEdge, MainWindow.selectedVertexIndex, strArr[0]);
	    graph.setEdgeData(currentInEdge, MainWindow.selectedVertexIndex, strArr[1]);
	}
    }

    @Override
    public Object getData() {
	if (!isGoneOut) {
	    String[] arr = new String[2];
	    if (graph.isEdgeExist(currentInEdge, MainWindow.selectedVertexIndex)) {
		arr[0] = graph.getEdgeWeight(currentInEdge, MainWindow.selectedVertexIndex).toString();
		arr[1] = graph.getEdgeData(currentInEdge, MainWindow.selectedVertexIndex).toString();
		return arr;
	    } else {
		return null;
	    }
	} else {
	    return null;
	}
    }
    
    @Override
    public GraphEdge getEdge() {
	GraphEdge edge = new GraphEdge();
	edge.edgeData = ((String[]) getData())[0];
	edge.edgeWeight = ((String[]) getData())[0];
	edge.startVertexIndex = currentInEdge;
	edge.endVertexIndex = MainWindow.selectedVertexIndex;
	return edge;
    }
}
